package com.idc.resource.manager;

import com.idc.resource.dal.dto.TMenuInfo;
import com.idc.resource.dal.mapper.TMenuInfoMapper;
import com.idc.resource.enums.ErrorCodeEnum;
import com.idc.resource.exception.IdcServiceException;
import com.idc.resource.model.MenuTree;
import com.idc.resource.util.BeanMapperUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 菜单管理
 * Created by Administrator on 2017/7/4 0004.
 */
@Slf4j
@Component
public class MenuManager {
    @Autowired
    private TMenuInfoMapper tMenuInfoMapper;

    /**
     * 根据用户id获取用户的权限菜单
     * @param userId 用户id
     * @return 权限菜单
     */
    public List<MenuTree> getMenuTree(Long userId){
        try {
            List<TMenuInfo> menuInfoList ;
            if(userId==null) {
                menuInfoList = tMenuInfoMapper.selectAll();
            }else {
                menuInfoList = tMenuInfoMapper.selectByUserId(userId);
            }
            Map<Integer,MenuTree> treeMap = new HashMap<Integer, MenuTree>();
            List<MenuTree> menuTrees = new ArrayList<MenuTree>();
            for (TMenuInfo tMenuInfo:menuInfoList){
                MenuTree menuTree ;
                if(treeMap.containsKey(tMenuInfo.getId())){
                    BeanMapperUtil.copy(tMenuInfo,treeMap.get(tMenuInfo.getId()));
                }else {
                    menuTree = BeanMapperUtil.objConvert(tMenuInfo,MenuTree.class);
                    if(tMenuInfo.getParentId()!=null){
                        MenuTree parentMenu = treeMap.get(tMenuInfo.getParentId())==null?new MenuTree():treeMap.get(tMenuInfo.getParentId());
                        parentMenu.setId(tMenuInfo.getParentId());
                        List<MenuTree> childes = parentMenu.getChildMenu()==null?new ArrayList<MenuTree>():parentMenu.getChildMenu();
                        childes.add(menuTree);
                        parentMenu.setChildMenu(childes);
                        treeMap.put(parentMenu.getId(),parentMenu);
                    }else {
                        menuTrees.add(menuTree);
                    }
                    treeMap.put(menuTree.getId(),menuTree);
                }
            }
            return menuTrees;
        }catch (Exception e){
            log.error("根据用户id获取用户权限失败，原因:",e);
            throw new IdcServiceException(ErrorCodeEnum.SYSTEM_ERROR.getCode(),ErrorCodeEnum.SYSTEM_ERROR.getDesc());
        }
    }


}
